/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="onePageTable">
  <div class="commonTablePanel openatc-basicdata">
    <div class="common-table-header" style="display:inline-block;width:100%;">
      <div class="common-table-title-container">
        <div class="common-table-title">
          <i class="iconfont icon-jichushujutongji"></i>
          <span>{{$t('openatc.main.basicdatastatistics')}}</span>
          <span class="separator">|</span>
        </div>
      </div>
      <div class="filter-container">
        <div class="filters">
            <span class="header-span">{{$t('openatc.common.orgnizations') }}：</span>
            <el-select style="width: 120px;" @clear="getTree()" v-model="formId" clearable ref="selectTree">
            <el-option
            :key="form.id"
            :value="form.id"
            :label="form.label"
            hidden
            >
            </el-option>
            <el-tree
            :data="datalist"
            default-expand-all
            :props="defaultProps"
            @node-click="handleClickNode"
            node-key="id">
            </el-tree>
            </el-select>
        </div>
        <div class="filters">
            <el-input
            @keyup.enter.native="getdevs()"
            v-model="devsfilter"
            :placeholder="$t('openatc.common.searchplaceholder')"
            style="width: 200px;">
            <el-button
                slot="append"
                @click="getdevs"
                icon="el-icon-search"
              ></el-button>
            </el-input>
        </div>
        <div class="filters">
          <el-date-picker
            style="width: 390px;"
            v-model="date"
            @change="changeTime"
            type="datetimerange"
            align="right"
            unlink-panels
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </div>
        <div class="filters">
          <el-button type="primary" @click="leadingOutData">{{$t('openatc.record.export')}}</el-button>
        </div>
      </div>
    </div>
    <div class="atc-table" id="footerBtn">
      <el-table
        :data="tableData"
        size="mini"
        :max-height="tableHeight"
        style="width: 100%;font-size: 14px;"
        :default-sort = "{prop: 'agentid', order: 'ascending'}"
        v-loading.body="listLoading">
        <el-table-column
        type="index"
        align="center">
        </el-table-column>
        <el-table-column
        prop="agentid"
        :label="$t('openatc.devicemanager.crossid')"
        :sort-method="sortAgentId"
        sortable
        align="center"
        width="220">
        </el-table-column>
        <el-table-column
        prop="name"
        :label="$t('openatc.devicemanager.devicename')"
        align="center"
        width="240">
        </el-table-column>
        <el-table-column
        prop="code"
        :label="$t('openatc.common.orgnizations')"
        align="center">
        </el-table-column>
        <el-table-column
          width="160"
          prop="patternUpdateTime"
          :label="$t('openatc.basic.patternUpdateTime')"
          align="center">
        </el-table-column>
        <el-table-column
          prop="phaseCount"
          :label="$t('openatc.basic.phasenum')"
          align="center">
        </el-table-column>
        <el-table-column
          prop="overlapCount"
          :label="$t('openatc.basic.overlapnum')"
          align="center">
        </el-table-column>
        <el-table-column
          prop="patternCount"
          :label="$t('openatc.basic.patternnum')"
          align="center">
        </el-table-column>
        <el-table-column
          prop="planCount"
          :label="$t('openatc.basic.plannum')"
          align="center">
        </el-table-column>
        <el-table-column
          prop="dateCount"
          :label="$t('openatc.basic.datenum')"
          align="center">
        </el-table-column>
        <el-table-column
          prop="vehLampCount"
          :label="$t('openatc.basic.vehiclelightnum')"
          sortable
          align="center">
        </el-table-column>
        <el-table-column
          prop="pedLampCount"
          :label="$t('openatc.basic.peoplelightnum')"
          sortable
          align="center">
        </el-table-column>
      </el-table>
     <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.pageNum" :page-size="listQuery.pageRow" :total="totalCount" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" style='margin:0px;'>
    </el-pagination>
  </div>
  </div>
</div>
</template>

<script>
import { GetOrganizationList } from '../../api/organization'
import { elTreeModel } from '../../model/tree/eltreemodel'
import { getBasicData } from '../../api/device'
import moment from 'moment'
import { ExportHistoricalStatistics } from '../../utils/export'
import { getMessageByCode } from '../../utils/responseMessage'
export default {
  name: 'user',
  components: {},
  data () {
    return {
      defaultProps: {
        value: 'id',
        label: 'label',
        children: 'children'
      },
      pickerOptions: {
        shortcuts: [
          {
            text: this.$t('openatc.basic.today'),
            onClick (picker) {
              const end = new Date()
              const start = new Date(new Date().setHours(0, 0, 0, 0))
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: this.$t('openatc.basic.yesterday'),
            onClick (picker) {
              const start = new Date()
              start.setTime(start.getTime() - 24 * 60 * 60 * 1000)
              start.setHours(0, 0, 0, 0)
              const end = new Date()
              end.setTime(end.getTime() - 24 * 60 * 60 * 1000)
              end.setHours(23, 59, 59, 0)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: this.$t('openatc.basic.week'),
            onClick (picker) {
              var end = new Date()
              var week = end.getDay()
              // 一天的毫秒数
              var millisecond = 1000 * 60 * 60 * 24
              // 减去的天数
              var minusDay = week !== 0 ? week - 1 : 6
              // 本周 周一
              var monday = new Date(end.getTime() - minusDay * millisecond)
              const start = new Date(monday)
              start.setHours(0, 0, 0, 0)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: this.$t('openatc.basic.lastweek'),
            onClick (picker) {
              // 上周开始时间
              const starta = new Date()
              var first = starta.getDate() - starta.getDay() - 6
              var startDate = new Date(starta.setDate(first))
              const start = new Date(startDate)
              start.setHours(0, 0, 0, 0)
              //  上周结束时间
              var currentDate = new Date()
              var firsts = currentDate.getDate() - currentDate.getDay() - 6
              var last = firsts + 6
              var endDate = new Date(currentDate.setDate(last))
              const end = new Date(endDate)
              end.setHours(23, 59, 59, 0)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: this.$t('openatc.basic.month'),
            onClick (picker) {
              let currentDate = new Date()
              let currentMonth = currentDate.getMonth()
              // 获得当前年份4位年
              let currentYear = currentDate.getFullYear()
              // 求出本月第一天
              const start = new Date(currentYear, currentMonth, 1)
              const end = new Date()
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: this.$t('openatc.basic.lastmonth'),
            onClick (picker) {
              // let that = this
              // 获取当前时间
              var currentDate = new Date()
              // 获得当前月份0-11
              var currentMonth = currentDate.getMonth()
              // 获得当前年份4位年
              var currentYear = currentDate.getFullYear()
              // 获得上一个月的第一天
              if (currentMonth === 0) {
                currentMonth = 11 // 月份为上年的最后月份
                currentYear-- // 年份减1
                return new Date(currentYear, currentMonth, 1)
              } else {
                // 否则,只减去月份
                currentMonth--
              }

              const start = new Date(currentYear, currentMonth, 1)

              // 获取当前时间
              var currentDates = new Date()
              // 获得当前月份0-11
              var currentMonths = currentDates.getMonth()
              // 获得当前年份4位年

              // 当为12月的时候年份需要加1
              // 月份需要更新为0 也就是下一年的第一个月
              // eslint-disable-next-line no-unused-vars
              var currentYears = currentDates.getFullYear()
              if (currentMonths === 11) {
                currentYears++
                currentMonths = 0 // 就为
              } else {
                // 否则只是月份增加,以便求的下一月的第一天
                currentMonths++
              }

              // 一天的毫秒数
              var millisecond = 1000 * 60 * 60 * 24
              // 求出上月的最后一天
              var aa = new Date()
              var thisMonth = aa.getMonth()
              // 获得当前年份4位年
              var thisYear = aa.getFullYear()
              // 求出本月第一天
              var firstDay = new Date(thisYear, thisMonth, 1)
              var lastDay = new Date(firstDay.getTime() - millisecond)
              const end = new Date(lastDay)
              end.setHours(23, 59, 59, 0)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: this.$t('openatc.basic.year'),
            onClick (picker) {
              // 获取当前时间
              var currentDate = new Date()
              // 获得当前年份4位年
              var currentYear = currentDate.getFullYear()

              // 本年第一天
              const start = new Date(currentYear, 0, 1)
              // 本年最后一天
              const end = new Date(currentYear, 11, 31)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: this.$t('openatc.basic.lastyear'),
            onClick (picker) {
              // 获取当前时间
              var currentDate = new Date()
              // 获得当前年份4位年
              var currentYear = currentDate.getFullYear() - 1

              // 本年第一天
              const start = new Date(currentYear, 0, 1)
              // 本年最后一天
              const end = new Date(currentYear, 11, 31)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: this.$t('openatc.basic.firstquarter'),
            onClick (picker) {
              // 获取当前时间
              var currentDate = new Date()
              // 获得当前年份4位年
              var currentYear = currentDate.getFullYear()

              // 第一季度第一天
              const start = new Date(currentYear, 0, 1)
              // 第一季度最后一天
              const end = new Date(currentYear, 2, 31)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: this.$t('openatc.basic.secondquarter'),
            onClick (picker) {
              // 获取当前时间
              var currentDate = new Date()
              // 获得当前年份4位年
              var currentYear = currentDate.getFullYear()
              // 第一季度第一天
              const start = new Date(currentYear, 3, 1)
              // 第一季度最后一天
              const end = new Date(currentYear, 5, 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: this.$t('openatc.basic.thirdquarter'),
            onClick (picker) {
              // 获取当前时间
              var currentDate = new Date()
              // 获得当前年份4位年
              var currentYear = currentDate.getFullYear()
              const start = new Date(currentYear, 6, 1)
              const end = new Date(currentYear, 8, 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: this.$t('openatc.basic.fourthquarter'),
            onClick (picker) {
              // 获取当前时间
              var currentDate = new Date()
              // 获得当前年份4位年
              var currentYear = currentDate.getFullYear()
              const start = new Date(currentYear, 9, 1)
              const end = new Date(currentYear, 11, 31)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      date: this.getDefaultDate(),
      listLoading: false, // 数据加载等待动画
      datalist: [],
      formId: '',
      form: {
        id: '',
        label: '',
        code: ''
      },
      tableHeight: 700,
      screenHeight: window.innerHeight, // 屏幕高度
      tableData: [],
      devsfilter: '',
      listQuery: {
        pageNum: 1, // 页码
        pageRow: 50 // 每页条数
      },
      totalCount: 0 // 分页组件--数据总条数
    }
  },
  watch: {
    screenHeight: function () {
      // 监听屏幕高度变化
      this.tableHeight =
                window.innerHeight -
                document.querySelector('#footerBtn').offsetTop -
                60
    }
  },
  mounted: function () {
    var _this = this
    _this.$nextTick(function () {
      // window.innerHeight:浏览器的可用高度
      // this.$refs.table.$el.offsetTop：表格距离浏览器的高度
      // 后面的50：根据需求空出的高度，自行调整
      _this.tableHeight =
                window.innerHeight -
                document.querySelector('#footerBtn').offsetTop -
                60
      window.onresize = function () {
        // 定义窗口大小变更通知事件
        _this.screenHeight = window.innerHeight // 窗口高度
      }
    })
  },
  created () {
    this.getList()
    this.getTableData()
  },
  methods: {
    leadingOutData () {
      let exportarr = []
      if (this.tableData && this.tableData.length) {
        exportarr = this.tableData.map(hisdata => {
          let exportfield = {
            '路口ID': hisdata.agentid,
            '路口名称': hisdata.name,
            '组织机构': hisdata.code,
            '方案更新时间': hisdata.patternUpdateTime,
            '相位数': hisdata.phaseCount,
            '跟随相位数': hisdata.overlapCount,
            '方案数': hisdata.patternCount,
            '计划数': hisdata.planCount,
            '日期数': hisdata.dateCount,
            '机动车灯组数': hisdata.vehLampCount,
            '行人灯组数': hisdata.pedLampCount
          }
          return exportfield
        })
        ExportHistoricalStatistics(exportarr, `基础数据统计.xlsx`)
      }
    },
    getList () {
      // 查询所有
      GetOrganizationList().then(data => {
        if (data.data.code === '401') { // 判断用户是否在其他地方被踢出
          window.location.reload()
          return
        }
        if (data.data.success !== true) {
          this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        this.datalist = elTreeModel.CreateTreeByPath(data.data.data)
      })
    },
    getDefaultDate () {
      this.now = new Date()
      this.nowDayOfWeek = this.now.getDay() // 今天本周的第几天
      this.nowDay = this.now.getDate() // 当前日
      this.nowMonth = this.now.getMonth()
      this.nowYear = this.now.getYear()
      this.nowYear += (this.nowYear < 2000) ? 1900 : 0
      let end = new Date()
      // let start = new Date()
      // start.setTime(start.getTime() - 3600 * 1000)
      let start = new Date(new Date().setHours(0, 0, 0, 0))
      return [start, end]
    },
    changeTime () {
      this.getTableData()
    },
    getTableData () {
      this.listLoading = true
      // let beginTime = moment(this.date[0]).format('YYYY-MM-DD HH:mm:ss')
      // let endTime = moment(this.date[1]).format('YYYY-MM-DD HH:mm:ss')
      let reqData = {
        'pageNum': this.listQuery.pageNum,
        'pageRow': this.listQuery.pageRow,
        'search': this.devsfilter,
        'code': this.form.code
        // 'beginTime': beginTime,
        // 'endTime': endTime
      }
      if (this.date) {
        let beginTime = moment(this.date[0]).format('YYYY-MM-DD HH:mm:ss')
        let endTime = moment(this.date[1]).format('YYYY-MM-DD HH:mm:ss')
        reqData.beginTime = beginTime
        reqData.endTime = endTime
      }
      getBasicData(reqData).then(res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        this.listLoading = false
        this.tableData = res.data.data.content
        this.totalCount = res.data.data.total
      })
    },
    getTree () {
      this.listQuery.pageNum = 1
      this.form.id = ''
      this.form.code = ''
      this.form.label = ''
      this.getTableData()
    },
    // 节点点击事件
    handleClickNode (data) {
      this.formId = data.label
      this.form.id = data.id
      this.form.code = data.code
      this.form.label = data.label
      this.$refs.selectTree.blur()
      this.listQuery.pageNum = 1
      this.getTableData()
    },
    sortAgentId (obj1, obj2) {
      let val1 = obj1.agentid
      let val2 = obj2.agentid
      return val1 - val2
    },
    getdevs () {
      this.listQuery.pageNum = 1
      this.getTableData()
    },

    handleSizeChange (val) {
      // 改变每页数量
      this.listQuery.pageRow = val
      this.getTableData()
    },
    handleCurrentChange (val) {
      // 改变页码
      this.listQuery.pageNum = val
      this.getTableData()
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
